package com.mayikt;

/**
 * @Author: maplefire
 * @Description: 多线程死锁示例
 * @Date: 2022/06/17 15:27
 */
class ThreadDemo03 implements Runnable {

    private int count = 100;
    private Object obj = new Object();
    public volatile Boolean flag = true;

    public void run() {
        if (flag) {
            while (count > 0) {
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (obj) {
                    sale();
                }
            }
        }

        while (count > 0) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            sale();
        }
    }

    public synchronized void sale() {
        synchronized (obj) {
            if (count > 0) {
                System.out.println(Thread.currentThread().getName() + ",出售第" + (100 - count + 1) + "张票");
                count--;
            }
        }
    }
}

public class Test03 {
    public static void main(String[] args) throws InterruptedException {
        ThreadDemo03 threadDemo03 = new ThreadDemo03();
        Thread t1 = new Thread(threadDemo03, "窗口1");
        Thread t2 = new Thread(threadDemo03, "窗口2");
        t1.start();
        Thread.sleep(10);
        threadDemo03.flag = false;
        t2.start();
    }
}